using System;
using System.IO;

namespace CLELCore
{
	public class CLELFileWriter : ICLELWriter,IDisposable
	{
		//path to file to write to
		private String _path;
		private FileStream _writer;
		private bool _disposed;
		private bool _little_endian;

		public String Path
		{
			get
			{
				return _path;
			}
		}

		public bool IsLittleEndian
		{
			get
			{
				return _little_endian;
			}
			set
			{
				_little_endian = value;
			}
		}

		public CLELFileWriter(String path)
		{
			_path = path;
			_writer = new FileStream(path,FileMode.Create,FileAccess.Write);
			_disposed = false;
			_little_endian = true;
		}

		public void WriteByte(byte val)
		{
			if(_disposed)
				return;
			_writer.WriteByte(val);
		}

		public void WriteShort(short val)
		{
			if(_disposed)
				return;
			int i;
			if(_little_endian)
				for(i = 0;i < 2;i++)
					_writer.WriteByte(Bits.ByteFromShort(i,val));
			else
				for(i = 1;i >= 0;i--)
					_writer.WriteByte(Bits.ByteFromShort(i,val));
		}

		public void WriteInt(int val)
		{
			if(_disposed)
				return;
			int i;
			if(_little_endian)
				for(i = 0;i < 4;i++)
					_writer.WriteByte(Bits.ByteFromInt(i,val));
			else
				for(i = 3;i >= 0;i--)
					_writer.WriteByte(Bits.ByteFromInt(i,val));
		}

		public void WriteLong(long val)
		{
			if(_disposed)
				return;
			int i;
			if(_little_endian)
				for(i = 0;i < 8;i++)
					_writer.WriteByte(Bits.ByteFromLong(i,val));
			else
				for(i = 7;i >= 0;i--)
					_writer.WriteByte(Bits.ByteFromLong(i,val));
		}

		public void Write(byte[] buffer,int offset,int length)
		{
			if(_disposed)
				return;
			_writer.Write(buffer,offset,length);
		}
		
		public void Close()
		{
			Dispose();
		}

		//make sure that FileStream was disposed
		public void Dispose()
		{
			_writer.Flush();
			_writer.Dispose();
			_disposed = true;
		}
	}
}
